<template>
  <el-dialog v-model="visible" width="25rem" @close="onClose" :close-on-click-modal="false">
    <div class="py-[3.75rem]">
      <div class="text-[#333] text-2xl font-bold text-center ">扫码登录</div>
      <div class="text-[#666] text-sm text-center my-[1.25rem]">请使用手机微信扫描二维码</div>
      <div
        class="w-[15rem] h-[15rem] mx-auto flex items-center justify-center border-1 border-solid border-[#ccc] rounded-md overflow-hidden cursor-pointer relative"
        @click="generateQRCode">
        <canvas ref="qrcodeCanvas"></canvas>

        <div class="text-[#666] text-sm text-center  absolute flex items-center justify-center w-full h-full bg-white flex-col gap-[1.25rem]" v-if="isExpired">
            {{ errMsg }}
            <el-button type="primary" @click="generateQRCode">刷新</el-button>
        </div>
      </div>
      
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick, onUnmounted } from 'vue'
import { useModalStore } from '@/stores/modal'
import { useUserStore } from '@/stores/user'  // 假设有这个store用来存储用户信息

import QRCode from 'qrcode'
import { getLoginStatus, setLoginToken } from '@/api/user'
import { message } from '@/utils/message'
const modalStore = useModalStore()
const userStore = useUserStore()

const visible = ref(modalStore.showLoginModal)
const qrcodeCanvas = ref<HTMLCanvasElement | null>(null)
const pollingTimer = ref<NodeJS.Timer | null>(null)
const isExpired = ref(false)
const errMsg = ref('')
const generateQRCode = async () => {
  isExpired.value = false
  errMsg.value = '123'
  stopPolling()

  const token = generateToken()
  if (!qrcodeCanvas.value) return
  // 向后端发送token
  await setLoginToken(token);

  const url = 'https://lqs.biglongxia.com/app/login/zsxq/getAuthUrl/' + token
  console.log('url:',url)
  // 生成知识星球二维码
  await QRCode.toCanvas(qrcodeCanvas.value, url, {
    width: 180,
    margin: 0,
    color: {
      dark: '#000000',
      light: '#ffffff'
    }
  })

  // 开始轮询
  startPolling(token)
}

// 生成token
const generateToken = () => {
  return 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

// 开始轮询
const startPolling = (token: string) => {
  pollingTimer.value = setInterval(async () => {
    try {
      const res = await getLoginStatus(token)
      console.log(res, 'res')
      const { status, login, userId, nickname, avatar, userNo, errorMsg } = res as any
      switch (status) {
        case 0: // 未扫码
          break
        case 1: // 已扫码待授权
          break
        case 2: // 已授权成功
          // 存储用户信息
          userStore.setUserInfo({
            token,
            userId,
            nickname,
            avatar,
            userNo
          })
          message.success('登录成功')
          stopPolling()
          modalStore.closeLoginModal()
          window.location.reload()
          break
        case 3: // 授权失败
          console.log('errMsg:',errMsg)
          isExpired.value = true 
          errMsg.value = errorMsg || '授权失败'
          stopPolling()
          break
        case -1: // token不存在或已过期
          isExpired.value = true // 显示提示
          errMsg.value = '二维码已过期，请点击二维码刷新后重新扫码登录'
          stopPolling() // 停止轮询
          break
      }

    } catch (error) {
      console.error('轮询失败:', error)
      stopPolling()
    }
  }, 3000) // 每3秒轮询一次
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value as unknown as number)
    pollingTimer.value = null
  }
}
watch(() => modalStore.showLoginModal, val => {
  visible.value = val
  if (val) {
    nextTick(() => {
      generateQRCode()
    })
  } else {
    stopPolling()
  }
}, { immediate: true })

// 组件卸载时清理
onUnmounted(() => {
  stopPolling()
})
function onClose() {
  modalStore.closeLoginModal()
  stopPolling()
}
</script>